angular.module('ceo.services', [])

//子路由 隐藏 tabs
 .directive('showTabs', function($rootScope) {
     return {
        link: function(scope, element, attr) {
            $rootScope.shouldShowTabs = attr.showTabs;
            scope.$on('$ionicView.beforeEnter', function() {
                scope.$watch(attr.showTabs, function(value){
                  $rootScope.shouldShowTabs = value;
                });
            });
        }
    };
})


.directive('accordion', function() {
  return {
    link: function(scope, element, attrs) {
      // console.log(element);
      // scope.expended = false;
      scope.toggleItem = function(item){
        // scope.expended = !scope.expended;
        if (scope.isItemShown(item)) {
          scope.shownItem = null;
        } else {
          scope.shownItem = item;
        }
      };
      scope.isItemShown = function(item){
        return scope.shownItem === item;
      };
    }
  };
})

//基础服务
.factory('BaseService',function($rootScope,$q){
  return {
  };
})

/**
 * 获取产品分类模型数据
 * @param  {String}
 * @param  {Function} callback
 * @return {Object}  公共调用方法
 */
.factory('ProductCatalogService',function($rootScope,$q){
  var productCatalogsSubHandle = $rootScope.subscribe('product_catalogs');
  var catalogsData={};
  var getProCatalogs = function(filter){
    var defer=$q.defer();

    return defer.promise;//返回获取的数据promise
  };


  return {
 
    getProperty:function(id,callback){
      pull('getPropById',id).then(function(data){
        callback(data);
      });
    },
    list : function(callback){
      pull().then(function(data){
        callback(data);
      });
    }
  };
})


/**
 * 获取产品模型数据
 * @param  {String}
 * @param  {Function} callback
 * @return {Object}  公共调用方法
 */
.factory('ProductService',function($rootScope,$q){

  var productData={};
  var getProCatalogs = function(){
    var defer=$q.defer();

    return defer.promise;//返回获取的数据promise
  };


  return {
    getCatalogs:function(callback){
      pull('getCat').then(function(data){
        callback(data);
      });
    },
    getCatName:function(id,callback){
      pull('getCat').then(function(datas){
        for(var i in datas){
          if(datas[i].id == id){
            callback(datas[i].name);
            break;
          }
        }
      });
    },
    getProperty:function(id,callback){
      pull('getPropById',id).then(function(data){
        callback(data);
      });
    },
    list : function(callback){
      pull().then(function(data){
        callback(data);
      });
    }
  };
})


/** @deprecated **/
.factory('BrandService',function($rootScope){
  var subscriptionHandle = $rootScope.subscribe('product_brands');
  $rootScope.helpers({
    brand_list: function() {
      return ProductBrands.find({});
    }
  });
  return {
    getBrandList : function(callback){
      $rootScope.autorun(function() {
        if(subscriptionHandle.ready() && $rootScope.brand_list){
          callback($rootScope.brand_list);
        }
      });
    }
  };
})

//采购
.factory('PurchaseService',function($q,$http){

  var pull = function(type,orderId){
    var req = '//jxc.vfwan.com/purchase_json.php?type='+type;
    req = orderId?req+'&orderid='+orderId:req;
    var defer=$q.defer();
    $http.get(req, {cache: true})
    .success(function(data){
      defer.resolve(data);//发送执行成功的消息，消息为inventoryData
    })
    .error(function(status, headers, config){
      defer.reject();//执行失败
    });
    return defer.promise;//返回获取的数据
  };
  var getStatusTxt = function(index){
    switch(index){
      case 0:
        return '已作废';
      case 1:
        return '计划';
      case 2:
        return '已下单';
      case 3:
        return '配送中';
      case 4:
        return '已收货';
      case 5:
        return '已入库';
    }
  };
  return {
    getOrderCount : function(type,callback){
      pull(type).then(function(data){
        callback(data);
      });
    },
    list : function(type,callback){
      var orderedData=[];
      pull(type).then(function(data){
        var today = new Date();
        today = Date.parse(new Date(today.getFullYear(),today.getMonth(),today.getDate(),0,0,0)) / 1000;

        for(var i=0;i<data.length;i++){
          var orderTime = parseInt(data[i].date);
          var dayInx = Math.ceil((today-orderTime)/86400);
          dayInx = dayInx<0?0:dayInx;
          if(!orderedData[dayInx]) orderedData[dayInx]={};

        　if (orderTime>today) {
            if(!orderedData[dayInx].divider) orderedData[dayInx].divider = '今日';
          }else if(orderTime>today-86400){
            if(!orderedData[dayInx].divider) orderedData[dayInx].divider = '昨日';
          }else if((today-orderTime)/86400<20){
            if(!orderedData[dayInx].divider) orderedData[dayInx].divider = dayInx+'日前';
          }else{
            var index=new Date(orderTime*1000);
            index = index.getFullYear()+'年'+index.getMonth()+"月"+index.getDate()+"日";
            if(!orderedData[dayInx].divider) orderedData[dayInx].divider = index;
          }
          if(!orderedData[dayInx].list) orderedData[dayInx].list=[];

          switch(data[i].return){
            case 1:
              data[i].returnTxt = '部分退货';
              break;
            case 2:
              data[i].returnTxt = '全部退货';
              break;
          }
          orderedData[dayInx].list.push(data[i]);

        }
        for(var j = 0 ;j<orderedData.length;j++){
          if(orderedData[j] === "" || typeof(orderedData[j]) == "undefined"){
            orderedData.splice(j,1);
            j--;
          }
        }
        callback(orderedData);
      });
    },
    getOne: function(itemId,callback){
      pull('getone',itemId).then(function(data){
        data.statusTxt=getStatusTxt(data.status);
        callback(data);
      });
    }
  };
})

//供应商
.factory('SupplierService',function($q,$http){

  var pull = function(type){
    var req = '//jxc.vfwan.com/supplier_json.php';
    var defer=$q.defer();
    $http.get(req, {cache: true})
    .success(function(data){
      defer.resolve(data);//发送执行成功的消息，消息为inventoryData
    })
    .error(function(status, headers, config){
      defer.reject();//执行失败
    });
    return defer.promise;//返回获取的数据
  };
  return {
    list : function(callback){
      pull().then(function(data){
        callback(data);
      });
    }
  };
})

//新闻rss
.factory('FeedService',function($q,$http,$sce){

    var url="http://news.baidu.com/n?cmd=1&class=cell&tn=rss",
        feedData = []; //进入首页后被初始化
    var service = {
      parseFeed : function(){
        var defer=$q.defer();
          $http.get(
            "https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20xml(5)%20where%20url%20%3D%20'http%3A%2F%2Fwww.cnmo.com%2Frss%2Fdoc.xml'%20limit%205&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys",
            {cache: true}
          )
          .success(function(data){
            feedData=data.query.results.rss.channel.item;
            for(var i=0;i<6;i++){
              feedData[i].pubDate = new Date(feedData[i].pubDate);
              feedData[i].description = feedData[i].description.replace(/(　*\t*\s*)(【(<\/?a[^>]*>)?手机中国([^】]*)】)/g,"");
            }
            feedData.splice(5,feedData.length);
            window.localStorage.entries = JSON.stringify(data.query.results.rss.channel.item);
            defer.resolve(feedData);//执行成功
          })
          .error(function(){
            if(window.localStorage.entries !== undefined) {
              feedData = JSON.parse(window.localStorage.entries);
            }
            defer.resolve(feedData);//执行成功

        });

        return defer.promise;//返回获取的数据
      },
      getOne : function(id){
        // console.log(service.feedData);
        return feedData[id-1];//返回获取的数据
      }
    };
    return service;
})

//递归列表
.directive('treeView',[function(){
 return {
    restrict: 'AE',
    template: '<div class="list tree-view">'+
                '<div ng-repeat="item in treeData" ng-include="recursionTemplate"></div>'+
              '</div>',
    scope: {
      recursionTemplate:'@', 
      treeData: '=', 
      canChecked: '=', 
      textField: '@', 
      leafIcon: '@', 
      preHref: '@',
      valueField:'@',
      itemClicked: '&',
      itemCheckedChanged: '&',
      initExpend:'@',
      expendAll:'&'
    },
    controller:['$scope', function($scope){
       $scope.itemExpended = function(item, $event){
         item.$$isExpend = ! item.$$isExpend;
         $event.stopPropagation();
       };

       $scope.getItemIcon = function(item){
         var isLeaf = $scope.isLeaf(item);
         if(isLeaf){
           return $scope.leafIcon;
         }
         return item.$$isExpend ? 'icon ion-minus': 'icon ion-plus';
       };

       $scope.isLeaf = function(item){
        return !item.children || !item.children.length;
       };
       $scope.warpCallback = function(callback, item, $event){
          ($scope[callback] || angular.noop)({
           $item:item,
           $event:$event
         });
       };
     }]
   };
 }]);
